<template>
  <div class="bar-gadget-css" :id="id">
    <Portal to="right-disable"  style="width:100;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height: '100%',border:0}">
        <el-card shadow="never"
                 :style="{height: '100%',border:0}"
                 class="aui-card--fill">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting&&gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section control-section2">
              <div class=content-wrapper
                   style="width:100%;height:100%;">
                <!-- <div v-if="isHasData"
                   :id="selfGadgetUuid"
                   style="width:100%;height:100%;"></div> -->
                <ejs-accumulationchart v-if="isHasData"
                                       ref="funnel"
                                       :id="selfGadgetUuid"
                                       style="display:block;  width: 100%;height:100%"
                                       :legendSettings="legendSettings"
                                       :enableAnimation="false"
                                       :pointClick="onClick">
                  <e-accumulation-series-collection>
                    <e-accumulation-series :dataSource="chartDataSource"
                                           xName="x"
                                           yName="y"
                                           :neckWidth="neckWidth"
                                           :neckHeight="neckHeight"
                                           :explode="explode"
                                           :dataLabel="dataLabel"
                                           height="80%"
                                           width="60%"
                                           type="Funnel"></e-accumulation-series>
                  </e-accumulation-series-collection>
                </ejs-accumulationchart>
                <div v-else
                     class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <div style="position:absolute;left:9999px;">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType='notgridgadget' />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
// import * as Echarts from 'echarts'
import { getUUID } from '@/utils'

export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },

  data: function () {
    return {
      chartDataSource: [],
      neckWidth: '15%',
      neckHeight: '18%',
      dataLabel: {
        visible: true,
        position: 'Outside',
        connectorStyle: { length: '6%' },
        name: 'text'
      },
      explode: false,
      // tooltip: { enable: true, format: '$' + '{point.x} : <b>' + '$' + '{point.y}</b>' },
      legendSettings: {
        visible: false
      },
      selfGadgetUuid: 'selector' + getUUID(),
      repeatNumber: 0,
      chartOption: {
        animation: 'auto',
        title: {
          text: 'Funnel',
          left: 'center'
        },
        legend: {
          // type: 'scroll',
          top: 20,
          width: '90%',
          data: ['Show', 'Click', 'Visit', 'Inquiry', 'Order']
        },
        grid: {
          top: 64,
          left: '3%',
          right: '3%',
          bottom: 30,
          width: '94%',
          height: '80%',
          containLabel: true
        },

        series: []
      },
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      theme: 'Material',
      dataSource: [{ name: 'a', data: [{ x: 0, y: 0 }] }],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      dataSource1: null,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'charthourglassgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'charthourglassgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      conditionFormat: [],
      linkedDatasetList: []
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    // this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  updated: function() {
    this.$nextTick(function() {
      this.$refs.funnel.ej2Instances.refresh();
      this.$refs.funnel.ej2Instances.removeSvg();
      this.$refs.funnel.ej2Instances.refreshSeries();
      this.$refs.funnel.ej2Instances.refreshChart();
    });
  },
  methods: {
    formatHover (params) {
      return '<span>' + params.seriesName + '</span><br />' +
        '<span>' + params.data.label + '</span>:   <span>' + params.data.value + '<span>'
    },
    updateChart (originData, data) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData, data)
        }, 1000)
      } else if (!Array.isArray(originData) || (Array.isArray(originData) && originData.length === 0)) {
        // Echarts.init(this.chartDom).dispose()
      } else {
        this.repeatNumber = 0
        if (this.gadgetSetting.valueFieldsNameMeasureL === '2') {
          let arr = []
          for (let index = 0; index < originData.length; index++) {
            const element = originData[index]
            let text = element[this.gadgetSetting.valueFieldsNameMeasureY] ? element[this.gadgetSetting.valueFieldsNameMeasureX] + ':  ' + this.setFormatFunctionForChart(this.queryFields, element[this.gadgetSetting.valueFieldsNameMeasureY], element[this.gadgetSetting.valueFieldsNameMeasureX]) : element[this.gadgetSetting.valueFieldsNameMeasureX] + ':  0'
            arr.push({
              x: element[this.gadgetSetting.valueFieldsNameMeasureX],
              y: element[this.gadgetSetting.valueFieldsNameMeasureY],
              text: text,
              drillThrough: this.gadgetSetting.valueFieldsNameMeasureY
            })
          }
          this.chartDataSource = arr
        } else if (this.gadgetSetting.valueFieldsNameMeasureL === '1') {
          let arr1 = []
          for (const key in originData[0]) {
            if (Object.hasOwnProperty.call(originData[0], key)) {
              const element = originData[0][key]
              let text = element ? key + ':  ' + this.setFormatFunctionForChart(this.queryFields, element, key) : key + ':  0'
              arr1.push({
                y: element || '',
                text: text,
                x: key,
                drillThrough: key
              })
            }
          }
          if (this.gadgetSetting.funnelListStorage) {
            let arr2 = []
            this.gadgetSetting.funnelListStorage.forEach(item => {
              let res = arr1.find(i => i.x === item.label)
              if (res) {
                arr2.push(res)
              }
            })
            this.chartDataSource = arr2.reverse()
          } else {
            this.chartDataSource = arr1.reverse()
          }
        }
      }
      this.updateGadgetLoadingStatus(!this.loading)
    },
    onClick (e) {
      try {
        if (!this.queryFields.some(i => i.dataType === 'dimension')) {
          if (!this.queryFields.some(i => i.dataType === 'measure')) {
            return false
          } else {
            if (this.gadgetSetting.valueFieldsNameMeasureL === '1') {
              this.queryId = this.queryFields.find(i => i.alias === this.chartDataSource[e.pointIndex].x).queryId
            } else {
              this.queryId = this.queryFields.find(i => i.alias === this.gadgetSetting.valueFieldsNameMeasureY).queryId
            }
            return this.findOriginData('')
          }
        } else if (this.queryFields.filter(i => i.dataType === 'dimension').length === 1) {
          let params = {
            seriesName: this.gadgetSetting.valueFieldsNameMeasureL === '2' ? this.queryData[e.pointIndex][this.gadgetSetting.valueFieldsNameMeasureX] : this.queryData[0][this.gadgetSetting.valueFieldsNameMeasureX],
            name: this.gadgetSetting.valueFieldsNameMeasureL === '2' ? this.queryData[e.pointIndex][this.gadgetSetting.valueFieldsNameMeasureX] : this.queryData[0][this.gadgetSetting.valueFieldsNameMeasureX]
          }
          // this.gadgetSetting.valueFieldsNameMeasureX = this.gadgetSetting.valueFieldsNameMeasureL === '2' ? this.queryData[e.pointIndex][this.gadgetSetting.valueFieldsNameMeasureX] : this.queryData[0][this.gadgetSetting.valueFieldsNameMeasureX]
          this.setDrillThroughInfo(params)
        } else {
          this.setDrillThroughInfoMoreDimension({ selectObj: this.queryData[e.pointIndex] })
        }
      } catch (error) {
        throw new Error(error)
      }
    },
    resetOptions (val, data) {
      val.series.push(JSON.parse(JSON.stringify(val.series[val.series.length - 1])))
      val.series[val.series.length - 1].type = 'line'
      val.series[val.series.length - 1].name = this.gadgetSetting.valueFieldsNameMeasureL
      val.series[val.series.length - 1].data.forEach((item, index) => {
        item.value = data[index][this.gadgetSetting.valueFieldsNameMeasureL]
      })
      return val
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        this.$refs.funnel.ej2Instances.refresh()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    upgradeGadgetSetting (setting) {

    },
    contrastObj (oreginObj, newobj) {
      let newfunnelListStorage = {}
      for (let key of Object.keys(oreginObj)) {
        if (newobj.hasOwnProperty(key)) {
          newfunnelListStorage[key] = newobj[key]
        }
      }
      for (let key of Object.keys(newobj)) {
        if (!(oreginObj.hasOwnProperty(key))) {
          newfunnelListStorage[key] = newobj[key]
        }
      }
      return newfunnelListStorage
    },
    query (e) {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        _self.verifyHasData(res)
        if (res.config) {
          if (res.config.valueFieldsNameMeasureL === '1') {
            if (res.config.funnelListStorage) {
              // let currList = this.contrastObj(res.config.funnelListStorage, res.data[0])
              this.$root.eventBus.$emit('funnelDataList', res.config.funnelListStorage)
              // res.data[0] = currList
            } else this.$root.eventBus.$emit('funnelDataList', res.data[0])
          }
          if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
              _self.gadgetSetting =  this.dataInfo.gadgetSetting
            }else{
              _self._.merge(_self.gadgetSetting, res.config)
          }
        
          if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
            _self.gadgetSetting.headerDescription = ''
          }
          _self.upgradeGadgetSetting(_self.gadgetSetting)
        }

        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
          _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.fxFields = res.fxFields || []
        if (res.data) {
          this.currentTime = new Date()
          _self.chartDataSource = []
          _self.queryData = res.data
          _self.queryFields = res.selectFields
          _self.conditionFormat = res.conditionFormat
          _self.linkedDatasetList = res.datasetSync
          if (Array.isArray(this.queryFields) && this.queryFields.length === 0 && (Array.isArray(res.data) && res.data.length > 0)) {
            // _self.updateSqlChart(res.data)
          } else {
            _self.updateChart(this._.cloneDeep(res.data), this._.cloneDeep(res))
          }
        }
        this.autoRefreshQuery(e)
      }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        this.isHasData = false
        this.currentTime = new Date()
        _self.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      })
    },
    load (args) {
      args.chart.series[0].marker.dataLabel.font.color = '#000000'
    }
  }
})
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 110px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.bar-gadget-css {
  height: 100%;
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
